package com.yuxin.tongyi.lsll.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;

import com.yuxin.tongyi.lsll.R;
import com.yuxin.tongyi.lsll.main.LoginActivity;
import com.yuxin.tongyi.lsll.sub.InstallPackageActivity;

public class VersionService extends Service{

	//文件存储
//	private File updateDir = null;
//	private File updateFile = null;
	 /* 下载包安装路径 */
    private String savePath = "";  //"test/";
    private String saveFileName =  "/new_tongyi_lsll.apk";
    private String pathName = "/install";
    private  final int DOWN_ERROR = 1;
    private  final int DOWN_OVER = 2;
//    private boolean interceptFlag = false;
    private  Thread downLoadThread;
//    private int progress;
	//通知栏
	private  NotificationManager updateNotificationManager = null;
	private  Notification updateNotification = null;
	//通知栏跳转Intent
	private  Intent updateIntent = null;
	private  PendingIntent updatePendingIntent = null;
	//返回的安装包url
	private String apkUrl;
	int updateTotalSize = 0;
	
	    private Handler mHandler = new Handler(){
	    	public void handleMessage(Message msg) {
	    		switch (msg.what) {
				case DOWN_ERROR:
					updateNotification.setLatestEventInfo(VersionService.this,"乐贝通","下载失败，请重新下载！",updatePendingIntent);
                    updateNotificationManager.notify(0, updateNotification);//通知通知栏进度条
                    stopService(updateIntent);
					break;
				case DOWN_OVER:   //下载完成
					installApk();  //安装应用程序
					stopService(updateIntent);
					break;
				default:
					stopService(updateIntent);
					break;
				}
	    	};
	    };
	
	    
		
	@Override
	public void onCreate() {
		super.onCreate();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
	    //获取传值
//	    titleId = intent.getIntExtra("titleId",0);
		if(intent!=null) {
		apkUrl = intent.getStringExtra("apkUrl");
		savePath = intent.getStringExtra("savePath");
		if(savePath!=null&&!"".equals(savePath)) {
		   savePath = savePath+pathName;
		}
	    //创建文件
//	    if(android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())){
//	        updateDir = new File(Environment.getExternalStorageDirectory(),Global.downloadDir);
//	        updateFile = new File(updateDir.getPath(),getResources().getString(titleId)+".apk");
//	    }

	    this.updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	    this.updateNotification = new Notification();

	    //设置下载过程中，点击通知栏，回到主界面
	    //updateIntent = new Intent(this, LoginActivity.class);
	    updateIntent = new Intent();
	    updatePendingIntent = PendingIntent.getActivity(this,0,updateIntent,PendingIntent.FLAG_UPDATE_CURRENT);
	    //设置通知栏显示内容
	    updateNotification.icon = R.drawable.icon2;
	    updateNotification.tickerText = "开始下载";
	    updateNotification.setLatestEventInfo(this,"乐贝通","0%",updatePendingIntent);
	    
	    //发出通知
	    updateNotificationManager.notify(0,updateNotification);
	    //开启一个新的线程下载，如果使用Service同步下载，会导致ANR问题，Service本身也会阻塞
	    downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
		}
		
	    return super.onStartCommand(intent, flags, startId);
	}

	
	/**
	 * 下载线程
	 */
	private Runnable mdownApkRunnable = new Runnable() {
		InputStream is;
		FileOutputStream fos;
		 Message message = mHandler.obtainMessage();
		public void run() {
			try {
			    File file = new File(savePath);
				if (!file.exists()) {
					file.mkdirs();
				}
				File saveFile = new File(savePath+saveFileName);
				long downsize = downloadUpdateFile(apkUrl,saveFile);
				if(downsize==updateTotalSize) {
					message.what = DOWN_OVER;
    				mHandler.sendMessage(message);
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
				message.what = DOWN_ERROR;
				mHandler.sendMessage(message);
			} finally {
				try {
					if (fos != null) {
						fos.close();
					}
					if (is != null) {
						is.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	};
	
	/**
	 * 下载相关
	 * @param downloadUrl
	 * @param saveFile
	 * @return
	 * @throws Exception
	 */
	public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
        HttpURLConnection httpConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        Message message = mHandler.obtainMessage();
        long totalSize = 0;   //当前下载大小
        try {
    	    int downloadCount = 0; //下载进度
            int currentSize = 0;
            //int updateTotalSize = 0;
            URL url = new URL(downloadUrl);
            httpConnection = (HttpURLConnection)url.openConnection();
            httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
            if(currentSize > 0) {
                httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
            }
            httpConnection.setConnectTimeout(120000);
            httpConnection.setReadTimeout(120000);
            updateTotalSize = httpConnection.getContentLength();
            Log.i("update", updateTotalSize + "-------updateTotalSize-----------------");
            
            if (httpConnection.getResponseCode() == 404) {
                throw new Exception("fail!");
            }
            is = httpConnection.getInputStream(); 
            fos = new FileOutputStream(saveFile, false);
            byte buffer[] = new byte[4096];
            int readsize = 0;
            while((readsize = is.read(buffer)) > 0){
                fos.write(buffer, 0, readsize);
                totalSize += readsize;
                Log.i("update", totalSize + " totalSize-----------------------readsize-" + readsize);
                //每下载10%通知通知栏一次
                if((downloadCount == 0)||(int) (totalSize*100/updateTotalSize)-10>=downloadCount){ 
                    downloadCount += 10;
                    updateNotification.setLatestEventInfo(VersionService.this, "正在下载", (int)totalSize*100/updateTotalSize+"%", updatePendingIntent);
                    updateNotificationManager.notify(0, updateNotification);//通知通知栏进度条
                }       
            }
        }catch(Exception e){
        	message.what = DOWN_ERROR;
        	mHandler.sendMessage(message);
        	e.printStackTrace();
        }finally {
            if(httpConnection != null) {
                httpConnection.disconnect();
            }
            if(is != null) {
                is.close();
            }
            if(fos != null) {
                fos.close();
            }
        }
        return totalSize;
    }
	
	
	 /**
     * 安装apk
     * @param url
     */
	private void installApk(){
		File apkfile = new File(savePath+saveFileName);
        if (!apkfile.exists()) {
            return;
        }    
//        Intent i = new Intent(Intent.ACTION_VIEW);
//        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); 
//        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        
        Intent i = new Intent();
        i.putExtra("savePath",savePath);
        i.putExtra("saveFileName",saveFileName);
        i.setClass(this,InstallPackageActivity.class);
        updatePendingIntent = PendingIntent.getActivity(VersionService.this, 0, i, 0);
        updateNotification.defaults = Notification.DEFAULT_SOUND;//铃声提醒 
        updateNotification.setLatestEventInfo(VersionService.this, "乐贝通", "下载完成,点击安装。", updatePendingIntent);
        updateNotificationManager.notify(0, updateNotification);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
}
